﻿using CommonAdmin.Dto;
using CommonAdmin.Web.Controllers.Api;
using CommonAdmin.Web.Converter;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using System.Text.Json;
using CommonAdmin.Util;

namespace CommonAdmin.Web.Controllers
{
	public class BaseController : Controller
	{
		protected readonly ILogger<BaseController> _logger;
		protected readonly ISqlSugarClient _db;
		private readonly JsonSerializerOptions _options = new JsonSerializerOptions()
		{
			DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
			PropertyNameCaseInsensitive = true,
			//重新编码，解决中文乱码问题			
			Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,

		};
		public BaseController(ILogger<BaseController> logger, ISqlSugarClient db)
		{
			_logger = logger;
			_db = db;
			_options.Converters.Add(new DatetimeJsonConverter());
		}
		/// <summary>
		/// 存储日志
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="content"></param>
		/// <param name="oldData"></param>
		/// <param name="newData"></param>
		protected void SaveDbLog<T>(string content, T oldData, T newData)
		{
			_db.Insertable<LogDto>(new LogDto()
			{
				UserId = HttpContext.Session.GetString(Constants.Session_Key_UserId),
				Content = content,
				OldData = JsonSerializer.Serialize<T>(oldData, _options),
				NewData = JsonSerializer.Serialize<T>(newData, _options),
			}).ExecuteCommand();
		}
		protected void LogError(Exception ex, string msg)
		{
			_logger.LogError(ex, msg);
		}
		protected UserDto GetCurrentUser()
		{
			string userId = HttpContext.Session.GetString(Constants.Session_Key_UserId);
			return _db.Queryable<UserDto>().First(u => u.Id == userId);
		}
	}
}
